<template>
  <div id="app">
    <!-- 面包屑导航 -->
    <el-breadcrumb separator="|">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片区域 -->
    <el-card>
      <!-- 警告提示文案 -->
      <el-alert
        title="添加商品信息"
        type="info"
        show-icon
        center
        :closable="false"
      ></el-alert>
      <!-- 步骤条 -->
      <!-- 涉及到隐式转换知识："0"-0=0 -->
      <el-steps align-center :active="activeIndex - 0" finish-status="success">
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
      </el-steps>
      <!-- 大的form表单包裹在外 -->
      <el-form
        :model="addGoodsForm"
        :rules="addGoodsRules"
        ref="addGoodsRef"
        label-width="100px"
        label-position="top"
      >
        <!-- 标签页区域 -->
        <el-tabs
          :tab-position="tabPosition"
          v-model="activeIndex"
          @tab-click="handleClick"
          :before-leave="certificate"
        >
          <el-tab-pane label="基本信息" name="0">
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="addGoodsForm.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input
                v-model="addGoodsForm.goods_price"
                type="number"
              ></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input
                v-model="addGoodsForm.goods_number"
                type="number"
              ></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input
                v-model="addGoodsForm.goods_weight"
                type="number"
              ></el-input>
            </el-form-item>
            <el-form-item label="商品分类" prop="goods_cat">
              <el-cascader
                v-model="addGoodsForm.goods_cat"
                :options="cateList"
                :props="cascaderProps"
                @change="handleChange"
                clearable
              ></el-cascader>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品参数" name="1">
            <el-form-item
              v-for="(item, i) in manyTabData"
              :key="i"
              :label="item.attr_name"
            >
              <!-- 多选框组 绑定的数据源是array类型-->
              <el-checkbox-group v-model="item.attr_vals">
                <el-checkbox
                  v-for="(cb, i) in item.attr_vals"
                  :key="i"
                  :label="cb"
                  border
                ></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品属性" name="2">
            <!-- 渲染表单的item项（商品属性） -->
            <el-form-item
              v-for="item in sticTabData"
              :key="item.attr_id"
              :label="item.attr_name"
            >
              <!-- input 绑定的数据源是object类型-->
              <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品图片" name="3">
            <!-- 点击上传图片按钮组件 -->
            <!-- list-type决定的事图片预览的效果 -->
            <el-upload
              class="upload-demo"
              :action="uploadURL"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              list-type="picture"
              :headers="headerObj"
              :on-success="tempics"
            >
              <el-button size="small" type="primary">点击上传</el-button>
              <div slot="tip" class="el-upload__tip">
                只能上传jpg/png文件，且不超过500kb
              </div>
            </el-upload>
          </el-tab-pane>
          <el-tab-pane label="商品内容" name="4">
            <quill-editor
              v-model="addGoodsForm.goods_introduce"
              ref="myQuillEditor"
            />
            <!-- 添加商品按钮 -->
            <el-button type="primary" style="margin-top:15px" @click="addGoods"
              >添加商品</el-button
            >
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>

    <!-- 图片预览对话框 -->
    <el-dialog title="提示" :visible.sync="upLoaddialogVisible" width="30%">
      <img :src="previewPath" alt="上传图片" />
    </el-dialog>
  </div>
</template>
<script>
import _ from 'lodash'

export default {
  data() {
    return {
      tabPosition: 'left',
      // 添加商品的数据对象
      addGoodsForm: {
        goods_name: '',
        goods_price: 0,
        goods_number: 0,
        goods_weight: 0,
        //级联选择器绑定的商品分类Array
        goods_cat: [],
        //上传的图片临时路径（对象）
        pics: [],
        //商品内容描述（富文本编辑）
        goods_introduce: '',
        // 商品参数
        attrs: []
      },
      // 标签页与步骤条联动绑定数据
      activeIndex: '0',
      addGoodsRules: {
        goods_name: [
          { required: true, message: '请添加商品名称', trigger: 'blur' }
        ],
        goods_price: [
          { required: true, message: '请添加商品价格', trigger: 'blur' }
        ],
        goods_number: [
          { required: true, message: '请添加商品数量', trigger: 'blur' }
        ],
        goods_weight: [
          { required: true, message: '请添加商品重量', trigger: 'blur' }
        ],
        goods_cat: [
          { required: true, message: '请添加商品分类', trigger: 'blur' }
        ]
      },
      // 级联选择器配置属性
      cascaderProps: {
        expandTrigger: 'hover',
        children: 'children',
        label: 'cat_name',
        value: 'cat_id'
      },
      // 级联选择器绑定的数据源
      cateList: [],
      //获取商品动态参数数据
      manyTabData: [],
      sticTabData: [],
      // 图片上传的api地址
      uploadURL: 'http://127.0.0.1:8888/api/private/v1/upload',
      // 上传图片组件请求头属性
      headerObj: {
        Authorization: window.sessionStorage.getItem('token')
      },
      // 控制预览图片显示与隐藏
      upLoaddialogVisible: false,
      // 预览图片地址
      previewPath: ''
    }
  },
  created() {
    this.getCateList()
  },
  methods: {
    // 获取商品分类数据
    async getCateList() {
      const { data: res } = await this.$http.get('categories', {
        params: { type: 3 }
      })
      if (res.meta.status !== 200) {
        this.$message.error('获取数据失败')
      }
      this.cateList = res.data
    },
    // 级联选择器触发事件
    handleChange() {
      console.log(this.addGoodsForm.goods_cat)
    },
    //页签切换前的判断,activeName与oldActiveName都是属于tabs的name属性,
    //分别代表即将进入的标签页名称与离开的标签页名称
    certificate(activeName, oldActiveName) {
      if (oldActiveName === '0' && this.addGoodsForm.goods_cat.length !== 3) {
        this.$message.error('请选择商品分类')
        return false
      }
    },
    // 标签页点击触发事件（1获取动态参数面板数据2获取商品属性）
    async handleClick() {
      if (this.activeIndex === '1') {
        const {
          data: res
        } = await this.$http.get(
          `categories/${this.addGoodsForm.goods_cat[2]}/attributes`,
          { params: { sel: 'many' } }
        )
        if (res.meta.status !== 200) {
          return this.$message.error('获取动态参数失败')
        }
        //把attr_vals中的字符串分割为数组
        res.data.forEach(item => {
          item.attr_vals =
            item.attr_vals.length === 0 ? [] : item.attr_vals.split(' ')
        })
        this.manyTabData = res.data
        console.log(this.manyTabData)
      } else if (this.activeIndex === '2') {
        const {
          data: res
        } = await this.$http.get(
          `categories/${this.addGoodsForm.goods_cat[2]}/attributes`,
          { params: { sel: 'only' } }
        )
        if (res.meta.status !== 200) {
          return this.$message.error('获取静态属性失败')
        }
        this.sticTabData = res.data
      }
    },
    // 图片上传组件预览效果
    handlePreview(file) {
      console.log(file)
      // 将上传成功的图片url地址传给图片预览组件
      this.upLoaddialogVisible = true
      this.previewPath = file.response.data.url
    },

    // 监听图片上传成功事件,将存储在服务器的图片保存到表单当中
    tempics(response) {
      // 1.将临时推按地址拼接成对象
      const picInfo = { pic: response.data.tmp_path }
      // 2.将此对象保存到表单数据当中
      this.addGoodsForm.pics.push(picInfo)
    },
    //移除图片，将pics相应的对象删除
    handleRemove(file) {
      console.log(file)
      // 1.找到要删除的图片临时存放路径
      const delPic = file.response.data.tmp_path
      // 2.存放在pics数组中的图片按照索引值找到相应的对象
      const i = this.addGoodsForm.pics.findIndex(item => item.pic === delPic)
      // 3.剪接数组中的对象
      this.addGoodsForm.pics.splice(i, 1)
    },
    // 添加商品
    addGoods() {
      this.$refs.addGoodsRef.validate(async valid => {
        if (!valid) {
          return this.$message.error('请填写必填项')
        }
        // 上传服务器的级联选择器分类id有要求用，是一个用逗号隔开的字符串
        const goodsForm = _.cloneDeep(this.addGoodsForm)
        goodsForm.goods_cat = goodsForm.goods_cat.join(',')
        // 处理动态参数上传
        this.manyTabData.forEach(item => {
          const newInfo = {
            attr_id: item.attr_id,
            attr_value: item.attr_vals
          }
          this.addGoodsForm.attrs.push(newInfo)
        })
        // 处理静态属性
        this.sticTabData.forEach(item => {
          const newInfo = {
            attr_id: item.attr_id,
            attr_value: item.attr_vals
          }
          this.addGoodsForm.attrs.push(newInfo)
        })
        // 将s所有准备好的数据复制到深拷贝的数据上
        goodsForm.attrs = this.addGoodsForm.attrs
        //发起请求添加商品
        //商品名称，必须是唯一的
        const { data: res } = await this.$http.post('goods', goodsForm)
        if (res.meta.status !== 201) {
          return this.$message.error('创建商品失败')
        }
        this.$message.success('创建商品成功')
        this.$router.push('/goods')
      })
    }
  }
}
</script>
<style lang="less" scoped>
.el-steps {
  margin: 15px 0;
}
.el-checkbox {
  margin: 0 9px 0 0 !important;
}
</style>
